package com.imooc.cls1;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class IoCContainer {
    private Map<String, Object> beans = new ConcurrentHashMap<String, Object>();

    public Object getBean(String beanId) {
        return this.beans.get(beanId);
    }

    public void setBean(Class<?> clazz, String beanId, String... paramBeanIds) {
        Object[] paramBeans = new Object[paramBeanIds.length];
        for (int i = 0; i < paramBeanIds.length; i++) {
            String paramBeanId = paramBeanIds[i];
            Object paramBean = getBean(paramBeanId);
            if (paramBean == null) {
                throw new RuntimeException("找不到对应的参数bean:" + paramBeanId);
            }
            paramBeans[i] = paramBean;
        }

        Object bean = null;
        for (Constructor constructor : clazz.getConstructors()) {
            try {
                bean = constructor.newInstance(paramBeans);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        if (bean == null) {
            throw new RuntimeException("找不到对应的构造器:" + beanId);
        }
        this.beans.put(beanId, bean);
    }
}
